//
//  ESAllTableViewController.m
//  Eyeshot
//
//  Created by admin on 15/7/7.
//  Copyright (c) 2015年 eyeshot. All rights reserved.
//

#import "ESAllTableViewController.h"
#import "ESNewPhotoModel.h"
#import "ESPhotoTableViewCell.h"
#import "ESVideoModel.h"
#import "ESVideoTableViewCell.h"
#import "ESDuanzi.h"
#import "ESDuanziTableCell.h"
#import "ESUserDetailViewController.h"
#import "ESPhotoDetailViewController.h"
#define kAllURL @"http://api.budejie.com/api/api_open.php?a=list&appname=baisishequ&asid=7AD5815A-BC34-40CA-A9BE-C9DAC444BC95&c=data&client=iphone&device=ios%20%E8%AE%BE%E5%A4%87&from=ios&jbk=0&mac=&market=&openudid=a3f29abd63d37c5476e06c24cad694f1182f25b2&page=0&per=20&sub_flag=1&type=1&udid=&uid=15094607&ver=3.6"

@interface ESAllTableViewController ()<ESPhotoTableViewCellDelegate,ESVideoTableViewCellDelegate,ESDuanziTableCellDelegate>
#import "ESCoverView.h"
#import <MediaPlayer/MediaPlayer.h>
#import "HMFileDownloader.h"
#import "ESMoviePlayer.h"
#import "UMSocial.h"
#define kAllURL @"http://api.budejie.com/api/api_open.php?a=list&appname=baisishequ&asid=7AD5815A-BC34-40CA-A9BE-C9DAC444BC95&c=data&client=iphone&device=ios%20%E8%AE%BE%E5%A4%87&from=ios&jbk=0&mac=&market=&openudid=a3f29abd63d37c5476e06c24cad694f1182f25b2&page=0&per=20&sub_flag=1&type=1&udid=&uid=15094607&ver=3.6"

@interface ESAllTableViewController ()<ESVideoTableViewCellDelegate,ESCoverViewDelegate,UMSocialUIDelegate>
@property (nonatomic, strong) NSMutableArray *allModelArr;
@property (nonatomic, strong) NSString *maxtime;//存放时间，刷新用
@property (nonatomic, assign) NSInteger startPage;
@property (nonatomic, assign) BOOL isLoad;//下拉刷新
@property (nonatomic, strong) ESUserDetailViewController *userDetailVC;
@property (nonatomic, strong) ESPhotoDetailViewController *photoDetailVC;//进入的大图的控制器
@property (nonatomic,strong) ESCoverView *coverView;
@property (nonatomic, strong) HMFileDownloader *fileDownloader;
//标识沙盒里是否存在缓存视频
@property (nonatomic,assign,getter = isExisting) BOOL existing;
@property (nonatomic,assign)BOOL fullScreen;
@property (strong,nonatomic) MPMoviePlayerController *player;
//来接受正在播放视频所在的cell
@property (nonatomic,strong) ESVideoTableViewCell *cell;
//来接受正在播放视频所在的按钮
@property (nonatomic,strong) UIButton *btn;

@end

@implementation ESAllTableViewController

- (void)requestAllData
{
    NSString *startPage = [NSString stringWithFormat:@"%ld",_startPage];
    NSString *reqStr = @"http://api.budejie.com/api/api_open.php";
    _maxtime = _maxtime? _maxtime : @"";
    NSDictionary *reqParas = @{@"a":self.type,
                               @"appname": @"baisishequ",
                               @"asid": @"7AD5815A-BC34-40CA-A9BE-C9DAC444BC95",
                               @"c": @"data",
                               @"client": @"iphone",
                               @"device": @"ios%20%E8%AE%BE%E5%A4%87",
                               @"from":@"ios",
                               @"jbk": @"0",
                               @"mac": @"",
                               @"market": @"",
                               @"maxtime":_maxtime,
                               @"openudid": @"a3f29abd63d37c5476e06c24cad694f1182f25b2",
                               @"page":startPage,
                               @"per":@20,
                               @"sub_flag":@1,
                               @"type":@1,
                               @"udid": @"",
                               @"uid":@"15094607",
                               @"ver":@"3.6",
                               };
    
    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    [requestManager GET:reqStr parameters:reqParas success:^(AFHTTPRequestOperation *operation, NSDictionary *dict) {
        
        if (_isLoad == YES)
        {
            [_allModelArr removeAllObjects];
        }
        
        NSArray *arr1 = dict[@"list"];
        NSDictionary *dict1 = dict[@"info"];
        _maxtime = dict1[@"maxtime"];
        for (NSDictionary *dic in arr1)
        {
            
            if ([(dic[@"cdn_img"]) isEqualToString:@""] || (dic[@"cdn_img"]) == nil)
            {
                ESDuanzi *model = [[ESDuanzi alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.allModelArr addObject:model];
            }else if ([(dic[@"videouri"]) isEqualToString:@""] && (![(dic[@"cdn_img"]) isEqualToString:@""] && (dic[@"cdn_img"]) != nil))
            {
                ESNewPhotoModel *model = [[ESNewPhotoModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.allModelArr addObject:model];
                
            }else if (![(dic[@"videouri"]) isEqualToString:@""])
            {
                ESVideoModel *model = [[ESVideoModel alloc] init];
               
                [model setValuesForKeysWithDictionary:dic];
                if (model.width == nil) {
                    continue;
                }
                [self.allModelArr addObject:model];
            }
            
            
        }
        
        if (_isLoad == YES)
        {
            [self.tableView.header endRefreshing];
            _isLoad = NO;
        }
        [self.tableView.footer endRefreshing];
 
        [self.tableView reloadData];
    
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        ESLog(@"%@",error);
    }];
}

- (void)loadNewData
{
    _isLoad = YES;
    [self requestAllData];
}
- (void)loadMoreData
{
    _startPage += 1;
    [self requestAllData];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.allModelArr = [[NSMutableArray alloc] initWithCapacity:0];
    _startPage = 0;
    //下拉刷新
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    //上拉加载
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    [self requestAllData];
   
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return self.allModelArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    id model = [self.allModelArr objectAtIndex:indexPath.row];
    
    if ([model isMemberOfClass:[ESDuanzi class]])
    {
        static NSString *IDDuan = @"allDCDuanzi";
        ESDuanziTableCell *cell = [tableView dequeueReusableCellWithIdentifier:IDDuan];
        if (!cell) {
            cell = [[ESDuanziTableCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:IDDuan];
        }
        cell.delegate = self;
        [cell setModel:model];
        
        return cell;
        
    }else if ([model isMemberOfClass:[ESNewPhotoModel class]])
    {
        static NSString *IDPhoto = @"allDCPhoto";
        ESPhotoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:IDPhoto];
        if (!cell) {
            cell = [[ESPhotoTableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:IDPhoto];
        }
        cell.delegate = self;
        [cell setPhotoModel:model];
        
        return cell;
    }else
    {
        static NSString *IDVedio = @"allDCVedio";
        ESVideoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:IDVedio];
        cell.delegate = self;
        if (!cell) {
            cell = [[ESVideoTableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:IDVedio];
        }
        
        [cell setModel:model];
        cell.delegate = self;
        return cell;
        
    }
    
    
}
#pragma mark - ESVideoTableViewCellDelegate
- (void)myCell:(ESVideoTableViewCell *)myCell didSelectButton:(UIButton *)btn model:(ESVideoModel *)model
{
    [self.coverView removeFromSuperview];
    if (!self.isExisting) {
        [myCell.indicatorView startAnimating];
        self.cell.playview.hidden = NO;
    }
    //避免同时播放多个视频,移除上个正在播放的视频，并把播放按钮显示出来
    if (self.cell.isPlaying) {
        [self.player.view removeFromSuperview];
        [self.coverView removeFromSuperview];
        self.cell.playview.hidden = NO;
    }
    
    
    //为了把当前播放视频的myCell传出去
    self.cell = myCell;
    self.btn = btn;
    //创建播放器
#warning 必须把所创建的MPMoviePlayerController设置为属性，否则无法播放，出现黑屏
    if (self.isExisting) {
        NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString *filepath = [caches stringByAppendingPathComponent:@"video.MP4"];
        self.player = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:filepath]];
    }else {
        self.player = [ESMoviePlayer playerWithUrl:model.videouri];
        _fileDownloader = [[HMFileDownloader alloc] init];
        // 需要下载的文件远程URL
        _fileDownloader.url = model.videouri;
        
        // 文件保存到什么地方
        NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString *filepath = [caches stringByAppendingPathComponent:@"video.MP4"];
        
        _fileDownloader.destPath = filepath;
        
        __weak typeof(self) weekself = self;
        _fileDownloader.completionHandler = ^{
            NSLog(@"--下载完毕--");
            weekself.existing = YES;
            
        };
        [self.fileDownloader start];
        
        [btn addSubview:myCell.indicatorView];
    }
    
    //为了避免播放开始出现黑屏，播放前先将播放器的view隐藏，等接到播放加载完成通知后显示
    self.player.view.hidden = YES;
    [self.player.view setFrame:btn.bounds];
    [btn addSubview:self.player.view];
    
    
    //点击后关闭自动播放，监听播放通知后播放
    self.player.shouldAutoplay = NO;
    [self.player prepareToPlay];
    //创建通知，监听播放结束后，把播放器视图移除
    NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
    [notification addObserver:self selector:@selector(moviePlayerPlaybackDidFinish:) name:MPMoviePlayerPlaybackDidFinishNotification  object:self.player];
    //通知全屏播放
    [notification addObserver:self selector:@selector(movieEventFullscreenHandler:) name:MPMoviePlayerDidEnterFullscreenNotification object:self.player];
    //通知退出全屏
    [notification addObserver:self selector:@selector(moviePlayerWillExitFullscreenHandler:) name:MPMoviePlayerWillExitFullscreenNotification object:self.player];
    //监听播放状态改变通知
    [notification addObserver:self selector:@selector(moviePlayerLoadStateDidChange:) name:MPMoviePlayerLoadStateDidChangeNotification object:self.player];
    //监听另一界面发出的移除视频播放的通知
    [notification addObserver:self selector:@selector(remove:) name:@"remove" object:nil];
    
}

- (void)remove:(NSNotification*)notification
{
    [self.coverView removeFromSuperview];
    self.cell.playview.hidden = NO;
    [self.player stop];
    self.player = nil;
}
- (void)moviePlayerLoadStateDidChange:(NSNotification*)notification
{
    //如果是加载完成状态，即可播放状态
    if (MPMovieLoadStatePlaythroughOK) {
        [self.player play];
        self.cell.isPlaying = YES;
        //为了充分避免黑屏出现，等完全进入播放状态后（延迟0.5S）显示播放窗口
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.player.view.hidden = NO;
            [self.cell.indicatorView stopAnimating];
        });
        
        
    }
}

//退出全屏
- (void)moviePlayerWillExitFullscreenHandler:(NSNotification*)notification
{
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIInterfaceOrientationPortrait] forKey:@"orientation"];
}

//进图全屏
- (void)movieEventFullscreenHandler:(NSNotification*)notification
{
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIInterfaceOrientationLandscapeRight] forKey:@"orientation"];
}

//播放完成移除播放视图
- (void)moviePlayerPlaybackDidFinish:(NSNotification*)notification
{
    [self.player.view removeFromSuperview];
    self.cell.playview.hidden = YES;
    self.cell.isPlaying = NO;
    //播放结束后加遮幕
    ESCoverView *coverView = [[ESCoverView alloc] init];
    self.coverView = [coverView coverWithFrame:self.btn.bounds SuperView:self.btn];
    self.coverView.delegate = self;
}


#pragma mark -ESCoverViewDelegate

- (void)ESCoverView:(UIView *)view didSelectReplayBtn:(UIButton *)btn
{
    self.existing = YES;
    [self.cell play:(UIButton *)[[btn superview] superview]];
    
}

- (void)ESCoverView:(UIView *)view didSelectShareBtn:(UIButton *)btn
{
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"55955b4c67e58e1c3a000c11"
                                      shareText:@"你要分享的文字"
                                     shareImage:@""
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToQzone,nil]
                                       delegate:self];
    
}
#pragma mark - UIScrollViewDelegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
#warning 为了避免视频播放时，用户滑动view，造成视频视图的重用
    //获得当前显示的cell对应的NSIndexPath，并存在数组indexPathArr中
    NSArray *indexPathArr = [self.tableView indexPathsForVisibleRows];
    //获得正在播放视频的cell的NSIndexPath
    NSIndexPath *indexPath = [self.tableView indexPathForCell:self.cell];
    //判断正在播放视频的cell是否在可见的cell中，如果不在将播放停止
    if (![indexPathArr containsObject:indexPath]) {
        [self.player pause];//此处加pause 是因为避免视图移除了，视频音效还有
        [self.player.view removeFromSuperview];
        [self.coverView removeFromSuperview];
        self.existing = NO;
        self.cell.playview.hidden = NO;
        self.cell.isPlaying = NO;
    }
}

    
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    id model = [self.allModelArr objectAtIndex:indexPath.row];
    
    
    if ([model isMemberOfClass:[ESDuanzi class]])
    {
        return  [ESDuanziTableCell heightForCellWithModel:model];
        
    }else if ([model isMemberOfClass:[ESNewPhotoModel class]])
    {
        return  [ESPhotoTableViewCell heightForCellWithModel:model];
        
    }else if ([model isMemberOfClass:[ESVideoModel class]])
    {
        return  [ESVideoTableViewCell getHeightForCellByModel:model];
    
    }
    
    return 0;
  
}

//进入用户页面详情
- (void)photoTableViewCell:(ESPhotoTableViewCell *)cell didSeletedUserBtn:(ESCellUserProfile *)btn
{
    self.userDetailVC = [[ESUserDetailViewController alloc] init];
    self.userDetailVC.userid = btn.userid;
    [self.navigationController pushViewController:self.userDetailVC animated:YES];
}

//cell的代理方法，让图片变大
- (void)photoTableViewCell:(ESPhotoTableViewCell *)cell didSeletedImage:(UIImage *)image
{
    self.photoDetailVC = [[ESPhotoDetailViewController alloc] init];
    self.photoDetailVC.imageV.image = image;
    [self presentViewController:self.photoDetailVC animated:YES completion:nil];
}

//进入用户页面详情
- (void)videoTableViewCell:(ESVideoTableViewCell *)cell didSeletedUserBtn:(ESCellUserProfile *)btn
{
    self.userDetailVC = [[ESUserDetailViewController alloc] init];
    self.userDetailVC.userid = btn.userid;
    [self.navigationController pushViewController:self.userDetailVC animated:YES];
}

////点击播放
//- (void)myCell:(ESVideoTableViewCell *)myCell didSelectButton:(UIButton *)btn model:(ESVideoModel *)model
//{
//    
//    
//    
//    
//}


//进入用户页面详情
- (void)duanZiTableViewCell:(ESDuanziTableCell *)cell didSeletedUserBtn:(ESCellUserProfile *)btn
{
    self.userDetailVC = [[ESUserDetailViewController alloc] init];
    self.userDetailVC.userid = btn.userid;
    [self.navigationController pushViewController:self.userDetailVC animated:YES];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
